package com.lazyframework.commons.support;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对ResponseModel快捷封装
 *
 * Create by lazy in 2019.09.17
 */
public class ResponseModels {

    private ResponseModels() {}

    //----------------------------Return a ResponseModel-------------------//

    public static <T> ResponseModel<T> ok() {
        return ok((T) null);
    }

    public static <T> ResponseModel<T> ok(T data) {
        return new ResponseModel<>(200, "ok", data);
    }

    public static ResponseModel error(ResponseStatus status) {
        return new ResponseModel<>(status, null);
    }

    public static <T> ResponseModel<T> error(ResponseStatus status, T data) {
        return new ResponseModel<>(status, data);
    }

    //----------------------------Return void and support with OutputStream-------------------//

    public static void ok(HttpServletResponse response) throws IOException {
        print(response, BasicResponseStatus.OK);
    }

    public static <T> void ok(HttpServletResponse response, T data) throws IOException {
        print(response, BasicResponseStatus.OK, data);
    }

    public static void forbidden(HttpServletResponse response) throws IOException {
        print(response, BasicResponseStatus.FORBIDDEN);
    }

    public static void unauthorized(HttpServletResponse response) throws IOException {
        print(response, BasicResponseStatus.UNAUTHORIZED);
    }

    public static void print(HttpServletResponse response, ResponseStatus status) throws IOException {
        print(response, status, null);
    }

    public static <T> void print(HttpServletResponse response, ResponseStatus status, T data) throws IOException {
        print(response, new ResponseModel<>(status, data));
    }

    public static void print(HttpServletResponse response, ResponseModel model) throws IOException {
        // 如果ResponseStatus的值小于等于1000且不等于200，则表示HTTP请求出错，设置对应的错误码
        int rsCode = model.getCode();
        if (rsCode < 1000 && rsCode != 200) {
            response.setStatus(rsCode);
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json");
        new ObjectMapper().writer().writeValue(response.getOutputStream(), model);
    }
}
